#!/usr/bin/env python
#coding=utf-8

from twisted.internet.protocol import Protocol, ClientFactory, ClientCreator
from twisted.protocols.basic import LineReceiver
from twisted.internet import protocol,reactor
from twisted.internet.reactor import callLater
from twisted.python import log
from twisted.python.logfile import DailyLogFile

import time,random
from common import data_analysis, components
import uuid
from conf.epconfig import EPConfig
from sys import stdout
import os
import platform

#引入环境变量，让python查找模块的时候到本目录查找
import sys
sys.path.append(os.getcwd())

fp = open(EPConfig['PID_FILE'],'w')
fp.write(str(os.getpid()))
fp.close()

if platform.system() == "Linux":
    from product.sysinfo import cpuinfo,baseinfo

elif platform.system() == "Windows":
    from product.sysinfo import baseinfo_win as baseinfo
    
else:
    pass


class Echo(Protocol):
    def __init__(self):
        self.recvBuf = ""

    def sendData(self,callid,data):
        outdata = data_analysis.sendData(callid,data)
        self.transport.write( outdata )

    def dataReceived(self, data):
        self.recvBuf += data
        cmddata = None
        while len(self.recvBuf):
            try:
                getdecode = data_analysis.decodedata(self.recvBuf,data)
                print "getdecode--->",getdecode
                if getdecode is True:
                    break
                if getdecode is False:
                    self.recvBuf=""
                    break
                self.recvBuf = getdecode[0]
                callid = getdecode[1]
                cmddata = getdecode[2]
            except:
                log.err()
                #repr将任意值转为字符串
                print( repr(getdecode) )
            if cmddata is not None:
                self.exeRecvData(cmddata,callid)
                
    #分析接收数据，并执行对应的任务脚本
    def exeRecvData(self,cmddata,callid):
        try:
            if not cmddata.has_key('taskid'):
                print "数据有问题，未发现任务号"
            else:
                
                taskid = cmddata.pop('taskid')
                oid = cmddata.pop('oid')
                
                try:
                    #载入执行函数
                    execfunc = components.load_func(cmddata.pop('py'))
                    print "cmddata====>",cmddata
                    result = execfunc(taskid,cmddata)
                except ImportError,e:
                    errmsg = "%s" % e
                    result = {'code':1,'errmsg':errmsg}
                    
                result['taskid'] = taskid
                result['act'] = 'end'
                result['oid'] = oid
                print "result===>",result
                self.sendData(callid,result)
                
        except:
            log.err()
            
            
    def connectionLost(self, reason):
        try:
            os.remove(EPConfig['PID_FILE'])
        except OSError,e:
            print "Not find pid file"
        print "---Client--connectionLost",reason

    def connectionMade(self):
        """
        #第一次连接时需要做的事情
        发送数据
        act:行为，告诉cm需要做什么
        """
        print 'Started to connect.'

        uid = loopi*1000+random.randint(1,999)
        if platform.system() == "Linux":
            
            server_asset_tag = uid
            server_cdrom = 0
            server_raidtype = ""

            comment = "linux"
            server_sn = baseinfo.serialnumber()
            is_virtual = 1
            
        elif platform.system() == "Windows":
            
            server_asset_tag = uid
            server_cdrom = 0
            server_raidtype = ""
            

            comment = "win"
            server_sn = baseinfo.serialnumber()
            is_virtual = 1
        
        data = {'act':'regos','server_height':1, 'server_asset_tag':server_asset_tag, 'server_cdrom':server_cdrom, 
                'server_raidtype':server_raidtype, 'comment':comment,
                'server_sn':server_sn,'is_virtual':is_virtual
                }
        
        print "data====>",data
        self.sendData(0,data)

class EchoClientFactory(ClientFactory):
    protocol = Echo

    def clientConnectionLost(self, connector, reason):
        print 'connection lost:', reason.getErrorMessage()
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print 'connection failed:', reason.getErrorMessage()
        connector.connect()

if __name__ == '__main__':

#    ln = './'+str(time.time())+'.log'
#    print ln
    #log.startLogging(DailyLogFile.fromFullPath(ln))
    loopi = 100
    #c = ClientCreator(reactor, EchoClientFactory)
    #c.connectTCP(HOST, PORT).addCallback(set_protocol,loopi).addErrback(end_protocol,loopi)

    #reactor.run()

    reactor.connectTCP(EPConfig['SERVER'], EPConfig['SERVER_PORT'], EchoClientFactory())
    reactor.run()